package com.easywb.springboot.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.easywb.springboot.aop.Release;
import com.easywb.springboot.mapper.blog.service.UserLoginService;
import com.easywb.springboot.mapper.blog.service.serviceImp.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class SysUserLoginInterceptor implements HandlerInterceptor {

    @Qualifier("UserLoginServiceImp")
    UserLoginService userService;

    @Autowired
    TokenService tokenService;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        String token = request.getHeader("token");// 从 http 请求头中取出 token

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有Release注释，有则跳过认证(放行)
        if (method.isAnnotationPresent(Release.class)) {
            return true;
        }
        //验证token
        if (token != null) {
            JSONObject data = tokenService.volidToken(token);
            if ((Boolean) data.get("type")) {
                return true;
            } else {
                throw new RuntimeException("未登录，无权限！");
            }
        } else {
            throw new RuntimeException("未登录，无权限！");
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
